package com.landmesure.bluetoothchat.view;

import android.Manifest;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.Fragment;
import android.app.ProgressDialog;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.content.ComponentName;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.ServiceConnection;
import android.content.pm.PackageManager;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.IBinder;
import android.os.Message;
import android.support.annotation.Nullable;
import android.support.annotation.RequiresApi;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.text.Html;
import android.util.Log;
import android.view.ContextThemeWrapper;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

import com.code.EntityType;
import com.code.JsonToJavabean;
import com.landmesure.bluetoothchat.BluetoothChatService;
import com.landmesure.bluetoothchat.DeviceListActivity;
import com.landmesure.bluetoothchat.LandCommunicationService;
import com.landmesure.bluetoothchat.R;
import com.landmesure.bluetoothchat.constant.Constant;
import com.landmesure.communication.BaseManager;
import com.landmesure.communication.CommunicationPlatform;
import com.landmesure.communication.ManagerFactory;
import com.landmesure.communication.ReadBoardEngine;
import com.landmesure.communication.ReadBoardManager;
import com.landmesure.communication.SendMessageService;
import com.code.CommandType;


import com.landmesure.settings.SettingActivity;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;

import static com.util.CodeFormatUtil.bytesToHexString;
import static com.util.CodeFormatUtil.hexStrToBinaryStr;


@RequiresApi(api = Build.VERSION_CODES.JELLY_BEAN)
public class BluetoothFragment extends Fragment {
    private static final String TAG = "BluetoothFragment";

    private Context mContext;


    public static int communicationType = CommandType.COMMAND_QUERY_OBJECT;//默认查询对象
    public static final int REQUEST_CONNECT_DEVICE = 1;
    private static final int REQUEST_ENABLE_BT = 2;

    //布局控件
    private TextView mTitle;
    private EditText mInputEditText;
    private Button breakButton;

    public static Handler handler;
    private String mConnectedDeviceName = null;
    private BluetoothAdapter mBluetoothAdapter = null;
    private BluetoothChatService bluetoothChatService = null;

    //第一次输入加入-->变量
    private int sum = 1;

    private ProgressDialog mDialog;
    public static String classKey = "通讯管理板1";
    public static ArrayList<EntityType> entityList = new ArrayList<>();//返回对象集合
    public static ArrayList<EntityType> boardList = new ArrayList<>();//返回板级对象列表
    public static Map<String, ArrayList> boardMap = new HashMap<>();//返回对象索引和值，存放entityList
    public static final Map<String, ArrayList> collectDataMap = new HashMap<>();//保存对象信源信宿

    public static LandCommunicationService landCommunicationServiceInstance;    //设备管理服务实例
    private BaseManager baseManager;
    private boolean isResume=false;
    private boolean mIsBind;
    private ServiceConnection mServiceConnection;

    class MyServiceConn implements ServiceConnection {

        @Override
        public void onServiceConnected(ComponentName name, IBinder iBinder) {
            LandCommunicationService.MyBinder myBinder;
            myBinder = (LandCommunicationService.MyBinder) iBinder;
            landCommunicationServiceInstance = myBinder.getInstance();
            landCommunicationServiceInstance.setBluetoothChatService(bluetoothChatService);
            mIsBind = true;
        }

        @Override
        public void onServiceDisconnected(ComponentName name) {
        }
    }

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        mContext = getActivity();

        //设置启动权限;
        setPermissions();

        //启动设备管理服务，并绑定它
        Intent intent = new Intent(mContext, LandCommunicationService.class);
        mContext.startService(intent);
        mContext.bindService(intent, mServiceConnection=new MyServiceConn(), Context.BIND_AUTO_CREATE);
    }

    /**
     * 设置Android6.0的权限申请
     */
    private static final String[] PERMISSIONS = new String[]{
            Manifest.permission.ACCESS_FINE_LOCATION,
            Manifest.permission.ACCESS_COARSE_LOCATION,
            Manifest.permission.WRITE_EXTERNAL_STORAGE,
            Manifest.permission.READ_EXTERNAL_STORAGE
    };

    private void setPermissions() {
        if (ContextCompat.checkSelfPermission(mContext, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED
                || ContextCompat.checkSelfPermission(mContext, Manifest.permission.READ_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
            ActivityCompat.requestPermissions((Activity) mContext, PERMISSIONS, 1);
        } else {
            Log.i(TAG, "权限申请ok");
        }
    }

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, Bundle savedInstanceState) {
        inflater = inflater.cloneInContext(new ContextThemeWrapper(mContext, R.style.AppThemea));
        View view = inflater.inflate(R.layout.layout_bluetooth_fragment, container, false);
        initView(view);

        // 得到当地的蓝牙适配器
        mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
        // 初始化Socket
        if (mBluetoothAdapter == null) {
            Toast.makeText(mContext, R.string.not_connected, Toast.LENGTH_LONG).show();
            ((Activity) mContext).finish();
            return super.onCreateView(inflater, container, savedInstanceState);
        }

        initHandler();
        CommunicationPlatform.handler=handler;
        baseManager = ManagerFactory.getRealManager("读取板子",handler);
        return view;
    }

    @Override
    public void onStart() {
        super.onStart();
        if (!mBluetoothAdapter.isEnabled()) {
            Intent enableIntent = new Intent(
                    BluetoothAdapter.ACTION_REQUEST_ENABLE);
            startActivityForResult(enableIntent, REQUEST_ENABLE_BT);
        } else {
            if (bluetoothChatService == null) {
                createBluetoothChatService();
            }
        }
    }

    @Override
    public synchronized void onResume() {


       super.onResume();
        if (bluetoothChatService != null) {

            if (bluetoothChatService.getState() == BluetoothChatService.STATE_NONE) {
                bluetoothChatService.start();
            }
        }
    }



    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        switch (requestCode) {
            case REQUEST_CONNECT_DEVICE:
                if (resultCode == Activity.RESULT_OK) {
                    String address = data.getExtras().getString(
                            DeviceListActivity.EXTRA_DEVICE_ADDRESS);
                    BluetoothDevice device = mBluetoothAdapter
                            .getRemoteDevice(address);
                    bluetoothChatService.connect(device);
                }
                break;
            case REQUEST_ENABLE_BT:
                if (resultCode == Activity.RESULT_OK) {
                    createBluetoothChatService();
                } else {
                    Toast.makeText(mContext, R.string.bt_not_enabled_leaving,
                            Toast.LENGTH_SHORT).show();
                    ((Activity) mContext).finish();
                }
        }
    }

    private void createBluetoothChatService() {
        bluetoothChatService = new BluetoothChatService();
        bluetoothChatService.setBaseManager(baseManager);
        bluetoothChatService.setHandler(handler);
    }

    private void initView(View view) {
        mInputEditText = view.findViewById(R.id.editText1);
        mInputEditText.setGravity(Gravity.TOP);
        mInputEditText.setSelection(mInputEditText.getText().length(),
                mInputEditText.getText().length());
        mInputEditText.clearFocus();
        mInputEditText.setFocusable(false);
        mTitle = view.findViewById(R.id.title_left_text);
        mTitle.setText(R.string.app_name);
        mTitle = view.findViewById(R.id.title_right_text);
        breakButton = view.findViewById(R.id.button_break);
        breakButton.setOnClickListener(new MyButtonClick());

        Button clean = view.findViewById(R.id.button_clean);
        clean.setOnClickListener(new MyButtonClick());
        Button read = view.findViewById(R.id.button_readData);
        read.setOnClickListener(new MyButtonClick());
        Button board = view.findViewById(R.id.button_readBoard);
        board.setOnClickListener(new MyButtonClick());
    }

    @SuppressLint("HandlerLeak")
    private void initHandler() {
        handler = new Handler() {
            @Override
            public void handleMessage(Message msg) {
                //蓝牙handler
                switch (msg.what) {
                    case Constant.MESSAGE_STATE_CHANGE:
                        switch (msg.arg1) {
                            case BluetoothChatService.STATE_CONNECTED:
                                mTitle.setText(R.string.title_connected_to);
                                mTitle.append(mConnectedDeviceName);
                                mInputEditText.setText("");
                                break;
                            case BluetoothChatService.STATE_CONNECTING:
                                mTitle.setText(R.string.title_connecting);
                                break;
                            case BluetoothChatService.STATE_LISTEN:
                            case BluetoothChatService.STATE_NONE:
                                mTitle.setText(R.string.title_not_connected);
                                break;
                        }
                        break;
                    case Constant.MESSAGE_WRITE:
                        byte[] writeBuf = (byte[]) msg.obj;
                        String writeMessage = bytesToHexString(writeBuf);
                        Log.i(TAG, "发送数据: " + writeMessage);
                        sum = 1;
                        mInputEditText.getText().append("\n发送消息：").append(writeMessage).append("\n");
                        break;
                    case Constant.MESSAGE_READ:
                        Bundle data = msg.getData();
                        String readMessage = data.getString("data");
                        if (sum == 1) {
                            mInputEditText.getText().append(Html.fromHtml("<font color=\"blue\">" + "\n接收消息:\n" + "</font>"));
                            sum++;
                        } else {
                            sum++;
                        }
                        mInputEditText.getText().append(Html.fromHtml("<font color=\"blue\">" + readMessage + "</font>"));
                        break;
                    case Constant.MESSAGE_DEVICE_NAME:
                        // 保存该连接装置的名字
                        mConnectedDeviceName = msg.getData().getString(Constant.DEVICE_NAME);
                        Toast.makeText(mContext.getApplicationContext(),
                                "已连接 " + mConnectedDeviceName, Toast.LENGTH_SHORT)
                                .show();
                        break;
                    case Constant.MESSAGE_TOAST:
                        Toast.makeText(mContext.getApplicationContext(),
                                msg.getData().getString(Constant.TOAST), Toast.LENGTH_SHORT)
                                .show();
                        break;
                    //业务handler
                    case Constant.ADD_DECODE_OBJECT_TO_SERIVCE:
                        entityList.add((EntityType) msg.obj);
                        landCommunicationServiceInstance.setData(entityList);
                        break;
                    case Constant.SET_ARGS_SUCCESS:
                        Toast.makeText(mContext.getApplicationContext(),
                                "执行成功", Toast.LENGTH_LONG)
                                .show();
                        break;

                    case Constant.SET_ARGS_ERROR:
                        Toast.makeText(mContext.getApplicationContext(),
                                "执行错误", Toast.LENGTH_LONG)
                                .show();
                        break;
                    case Constant.QUERY_MANAGEMENT_BOARD:
                    case Constant.QUERY_MEASUREMENT_BOARD:
                        closeProcessDialog();
                        ReadBoardEngine.readBoardEnd();
                        showDialog();
                        break;
                    case Constant.SEND_MESSAGE:
                        String ms = (String) msg.obj;
                        byte[] send = hexStrToBinaryStr(ms);
                        bluetoothChatService.write(send);
                        break;
                    default:
                        break;
                }
            }
        };
    }

    private void showProcessDialog(Context mContext) {

        // 声明一个等待框以提示用户等待
        mDialog = new ProgressDialog(mContext);
        mDialog.setTitle("提示信息");
        mDialog.setMessage("正在读取，请稍后...");
        mDialog.show();
        mDialog.setCancelable(false);
    }

    private void closeProcessDialog() {
        if (mDialog != null) {
            mDialog.setCancelable(true);
            mDialog.dismiss();
        }
    }

    private void showDialog() {
        int size = boardList.size();
        final String[] myList = new String[size + 1];
        myList[0] = "通讯管理板1";
        for (int i = 0; i < size; i++) {
            myList[i + 1] = boardList.get(i).getName() + boardList.get(i).getEcode();
        }
        AlertDialog.Builder builder = new AlertDialog.Builder(mContext);
        builder.setTitle("选择一个板级对象");
        builder.setItems(myList, new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                try {
                    dialogClick(which, myList[which]);
                } catch (Exception e) {
                    e.printStackTrace();
                }

            }
        });
        builder.show();
    }

    private void dialogClick(int index, String key) throws Exception {
        classKey = key;
        if (boardMap.containsKey(key)) {//是否已经查询
            landCommunicationServiceInstance.setData(boardMap.get(key));
            Intent intent = new Intent(mContext, SettingActivity.class);
            startActivity(intent);

        } else {
            if (unBluetoothConnected()) return;
            beforeReadBoard();
            ReadBoardEngine.isReadMeasureBoard = true;
            SendMessageService sendMessageService = new SendMessageService();
            sendMessageService.sendMessage(boardList.get(index - 1), Constant.QUERY_MEASUREMENT_BOARD, null,null);

        }
    }


    public class MyButtonClick implements View.OnClickListener {

        @Override
        public void onClick(View v) {
            try {
                onMyButtonClick(v);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }

    public void onMyButtonClick(View view) throws Exception {
        switch (view.getId()) {
            case R.id.button_clean:
                mInputEditText.setText("");
                sum = 0;
                break;
            case R.id.button_break:
                onConnectButtonClicked();
                break;
            case R.id.button_readData:
//                Intent intent = new Intent(getActivity(), WebViewActivity.class);
//                startActivity(intent);
                break;
            case R.id.button_readBoard:
                if (boardMap.containsKey("通讯管理板1")) {
                    showDialog();
                } else {
                    beforeReadBoard();
                    SendMessageService sendMessageService = new SendMessageService();
                    sendMessageService.sendMessage(null, Constant.QUERY_MANAGEMENT_BOARD, null,null);
                }
                break;
            default:
                break;


        }
    }

    public void beforeReadBoard() {
        if (unBluetoothConnected()) return;
        showProcessDialog(mContext);
        ReadBoardManager.doneMessage = new StringBuffer();
        ReadBoardManager.totalMessage = new StringBuffer();
        entityList = new ArrayList<>();
        ReadBoardEngine.init();
    }

    private boolean unBluetoothConnected() {
        if (bluetoothChatService.getState() != BluetoothChatService.STATE_CONNECTED) {
            Toast.makeText(mContext.getApplicationContext(),
                    "蓝牙未连接", Toast.LENGTH_SHORT)
                    .show();
            return true;
        }
        return false;
    }

    public void onConnectButtonClicked() {
        if (breakButton.getText().equals("连接") || breakButton.getText().equals("connect")) {
            Intent serverIntent = new Intent(mContext, DeviceListActivity.class);
            startActivityForResult(serverIntent, Constant.REQUEST_CONNECT_DEVICE);
            breakButton.setText(R.string.duankai);
            JsonToJavabean jsonToJavabean = new JsonToJavabean();
            jsonToJavabean.JsonToJavabean(mContext.getApplicationContext());
        } else {
            try {
                // 关闭蓝牙
                breakButton.setText(R.string.button_break);
                bluetoothChatService.stop();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }

    public static  void handlerSendMessage(Message message){
        handler.sendMessage(message);
    }
    @Override
    public void onDestroy() {
        super.onDestroy();
        if (mIsBind)
            mContext.unbindService(mServiceConnection);
    }
}
